// plugins/gatsby-source-list/gatsby-node.js
const axios = require('axios')
const createNodeHelpers = require('gatsby-node-helpers').default
const { paginate } = require('gatsby-awesome-pagination')

exports.sourceNodes = async ({ actions }, { apiUrl }) => {
    // 从 actions 中解构 createNode 创建节点的方法
    const { createNode } = actions
    let articles = await loadArticles(apiUrl)
    const { createNodeFactory, generateNodeId } = createNodeHelpers({
        typePrefix: 'articles'
    })
    
    const createNodeObject = createNodeFactory('list', node => {
        // 每次创建节点时都会执行的回调
        // 根据字符串生成默认 id
        node.id = generateNodeId('list', node.slug)
        return node
    })
    // 将数据添加到节点对象中并插入到数据层中
    articles.forEach(article => {
        // 根据数据 id 创建节点 id，如果节点没有 id，所有的数据都会被覆盖
        createNode(createNodeObject(article))
    })
}

async function loadArticles (apiUrl) {
    let limit = 100
    let offset = 0
    let result = []
    await load()
    async function load () {
        let { data } = await axios.get(`${apiUrl}/articles`, {
            params: { limit, offset }
        })
        result.push(...data.articles)
        // data.articlesCount 文章总数量
        if (result.length < data.articlesCount) {
            offset += limit
            await load()
        }
    }
    return result
}

exports.createPages = async ({ actions, graphql }) => {
    const { createPage } = actions
    let { data } = await graphql(`query {
        allArticlesList {
          nodes {
            slug
          }
        }
      }
    `)
    // Create your paginated pages
    paginate({
        createPage, // The Gatsby `createPage` function
        items: data.allArticlesList.nodes, // 需要分页的数据
        itemsPerPage: 10, // 每一页的数量
        pathPrefix: '/list', // 创建页面的访问地址 /list/1 /list/2
        component: require.resolve('../../src/templates/list.js'), // 模板
    })
}